package com.dayaokeji.coursetable;

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Color;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutCompat;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.dayaokeji.coursetable.bean.CourseModel;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * Created by Gorden on 2017/11/1.
 * 课程表View
 */

public class CourseTableView extends FrameLayout {

    private LinearLayout courseView;
    private LinearLayoutCompat weekNames;
    private LinearLayout sections;
    private LinearLayout weekPanel_1;
    private LinearLayout weekPanel_2;
    private LinearLayout weekPanel_3;
    private LinearLayout weekPanel_4;
    private LinearLayout weekPanel_5;
    private LinearLayout weekPanel_6;
    private LinearLayout weekPanel_7;

    private List<LinearLayout> mWeekViews = new ArrayList<>();
    private int itemHeight;
    private int maxSection = 12;

    private ItemCourseClickListener itemCourseClickListener;
    private final String[] Ts = new String[]{"M","T","W","T","F","S","S"};

    private static Date startDate;
    private static Date endDate;

    public CourseTableView(Context context) {
        this(context,null);
    }

    public CourseTableView(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs,0);
    }

    public CourseTableView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context);
    }

    private void init(Context context) {
        itemHeight = getResources().getDimensionPixelSize(R.dimen.sectionHeight);
        courseView = (LinearLayout) LayoutInflater.from(context).inflate(R.layout.course_table, null);

        weekNames = (LinearLayoutCompat) courseView.findViewById(R.id.weekNames);
        sections = (LinearLayout) courseView.findViewById(R.id.sections);
        weekPanel_1 = (LinearLayout) courseView.findViewById(R.id.weekPanel_1);
        weekPanel_2 = (LinearLayout) courseView.findViewById(R.id.weekPanel_2);
        weekPanel_3 = (LinearLayout) courseView.findViewById(R.id.weekPanel_3);
        weekPanel_4 = (LinearLayout) courseView.findViewById(R.id.weekPanel_4);
        weekPanel_5 = (LinearLayout) courseView.findViewById(R.id.weekPanel_5);
        weekPanel_6 = (LinearLayout) courseView.findViewById(R.id.weekPanel_6);
        weekPanel_7 = (LinearLayout) courseView.findViewById(R.id.weekPanel_7);

        mWeekViews.add(weekPanel_1);
        mWeekViews.add(weekPanel_2);
        mWeekViews.add(weekPanel_3);
        mWeekViews.add(weekPanel_4);
        mWeekViews.add(weekPanel_5);
        mWeekViews.add(weekPanel_6);
        mWeekViews.add(weekPanel_7);

        initWeekNameView();
        initSectionView();

        this.addView(courseView);
    }

    public static void setData(Date startDate,Date endDate) {
        CourseTableView.startDate = startDate;
        CourseTableView.endDate = endDate;
    }

    /**
     * 初始化课程表
     */
    public void setWeekCourseViewData(List<CourseModel>[] courseViewData) {
        if (courseViewData != null && courseViewData.length > 0) {
            for (int i = 0; i < mWeekViews.size(); i++) {
                initWeekPanel(mWeekViews.get(i), courseViewData[i]);
            }
        }
    }

    public void setItemCourseClickListener(ItemCourseClickListener itemCourseClickListener) {
        this.itemCourseClickListener = itemCourseClickListener;
    }

    public void initWeekPanel(LinearLayout ll, List<CourseModel> data) {

        if (ll == null || data == null || data.size() < 1)
            return;
        CourseModel firstCourse = data.get(0);
        ll.removeAllViews();
        for (int i = 0; i < data.size(); i++) {
            final CourseModel courseModel = data.get(i);

            if (courseModel.getSection() == 0 || courseModel.getSectionSpan() == 0)
                return;
            FrameLayout frameLayout = new FrameLayout(this.getContext());

//            CornerTextView tv = new CornerTextView(this.getContext(),
//                    ColorUtils.getCourseBgColor(courseModel.getCourseFlag()),
//                    dip2px(this.getContext(), 3));
            CornerTextView tv = new CornerTextView(this.getContext(),Color.parseColor("#FFFFFF"),
                    dip2px(this.getContext(), 3),Color.parseColor("#F1F1F1"));
            tv.setBackgroundDrawable(getResources().getDrawable(R.drawable.couse_bg));
            LinearLayout.LayoutParams frameLp = new LinearLayout.LayoutParams(
                    LinearLayout.LayoutParams.MATCH_PARENT,
                    itemHeight * courseModel.getSectionSpan());
            LinearLayout.LayoutParams tvLp = new LinearLayout.LayoutParams(
                    LinearLayout.LayoutParams.MATCH_PARENT,
                    LinearLayout.LayoutParams.MATCH_PARENT);

            if (i == 0) {
                frameLp.setMargins(0, (courseModel.getSection() - 1) * itemHeight, 0, 0);
            } else {
                frameLp.setMargins(0, (courseModel.getSection() - (firstCourse.getSection() + firstCourse.getSectionSpan())) * itemHeight, 0, 0);
            }
            tv.setLayoutParams(tvLp);
            tv.setGravity(Gravity.CENTER);
            tv.setTextSize(12);
            tv.setTextColor(Color.parseColor("#333333"));
            tv.setText(courseModel.getCourseName() + "\n @" + courseModel.getClassRoom());

            frameLayout.setLayoutParams(frameLp);
            frameLayout.addView(tv);
            frameLayout.setPadding(2, 2, 2, 2);
            ll.addView(frameLayout);
            firstCourse = courseModel;
            tv.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    if (itemCourseClickListener != null) {
                        itemCourseClickListener.onClick(view,courseModel);
                    }
                }
            });
        }
    }

    /**
     * 顶部周一到周日的布局
     **/
    @SuppressLint("SetTextI18n")
    private void initWeekNameView() {
        for (int i = 0; i < mWeekViews.size() + 1; i++) {
            TextView tvWeekName = new TextView(this.getContext());
            LinearLayoutCompat.LayoutParams lp = new LinearLayoutCompat.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
            lp.gravity = Gravity.CENTER | Gravity.CENTER_HORIZONTAL;
            if (i != 0) {
                lp.weight = 1;
                tvWeekName.setText(getT(i - 1)+"\n" + getDates(startDate, endDate).get(i - 1));
                if (i == getWeekDay()) {
                    tvWeekName.setTextColor(Color.parseColor("#FF0000"));
                } else {
                    tvWeekName.setTextColor(Color.parseColor("#4A4A4A"));
                }
            } else {
                lp.weight = 0.8f;
                tvWeekName.setText((startDate.getMonth()+1) + "月");
            }
            tvWeekName.setGravity(Gravity.CENTER_HORIZONTAL);
            tvWeekName.setTextColor(Color.parseColor("#333333"));
            tvWeekName.setLayoutParams(lp);
            weekNames.addView(tvWeekName);
        }
    }

    /**
     * 当前星期
     */
    public int getWeekDay() {
        int w = Calendar.getInstance().get(Calendar.DAY_OF_WEEK) - 1;
        if (w <= 0) {
            w = 7;
        }
        return w;
    }

    private String getT(int i) {
        if (i < Ts.length) {
            return Ts[i];
        }else{
            return "";
        }
    }

    /**
     * 当前月份
     */
    public int getMonth() {
        int w = Calendar.getInstance().get(Calendar.MONTH) + 1;
        return w;
    }

    /**
     * 得到一个星期日期时间
     * @return
     */
    public static String[] getWeekDates() {
        final String[] weeks = new String[7];
        Calendar calendar = Calendar.getInstance();
        setToFirstDay(calendar);
        for (int i = 0; i < 7; i++) {
            weeks[i] = String.valueOf(calendar.get(Calendar.DATE));
            calendar.add(Calendar.DATE, 1);
        }
        return weeks;
    }

    private static final int FIRST_DAY = Calendar.MONDAY;
    private static void setToFirstDay(Calendar calendar) {
        while (calendar.get(Calendar.DAY_OF_WEEK) != FIRST_DAY) {
            calendar.add(Calendar.DATE, -1);
        }
    }


    /**
     * 数字转换中文
     */
    public static String intToZH(int i) {
        String[] zh = {"零", "一", "二", "三", "四", "五", "六", "七", "八", "九"};
        String[] unit = {"", "十", "百", "千", "万", "十", "百", "千", "亿", "十"};

        String str = "";
        StringBuffer sb = new StringBuffer(String.valueOf(i));
        sb = sb.reverse();
        int r = 0;
        int l = 0;
        for (int j = 0; j < sb.length(); j++) {
            r = Integer.valueOf(sb.substring(j, j + 1));
            if (j != 0)
                l = Integer.valueOf(sb.substring(j - 1, j));
            if (j == 0) {
                if (r != 0 || sb.length() == 1)
                    str = zh[r];
                continue;
            }
            if (j == 1 || j == 2 || j == 3 || j == 5 || j == 6 || j == 7 || j == 9) {
                if (r != 0)
                    str = zh[r] + unit[j] + str;
                else if (l != 0)
                    str = zh[r] + str;
                continue;
            }
            if (j == 4 || j == 8) {
                str = unit[j] + str;
                if ((l != 0 && r == 0) || r != 0)
                    str = zh[r] + str;
                continue;
            }
        }
        if (str.equals("七"))
            str = "日";
        return str;
    }

    /**
     * 根据手机的分辨率从 dp 的单位 转成为 px(像素)
     */
    public static int dip2px(Context context, float dpValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }

    /**
     * 左边节次布局，设定每天最多12节课
     */
    private void initSectionView() {
        for (int i = 1; i <= maxSection; i++) {
            TextView tvSection = new TextView(this.getContext());
            LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, getResources().getDimensionPixelSize(R.dimen.sectionHeight));
            lp.gravity = Gravity.CENTER;
            tvSection.setGravity(Gravity.CENTER);
            tvSection.setTextColor(Color.parseColor("#787993"));
            tvSection.setText(String.valueOf(i));
            tvSection.setLayoutParams(lp);
            sections.addView(tvSection);
        }
    }


    public interface ItemCourseClickListener{
        void onClick(View view,CourseModel courseModel);
    }

    /**
     * 根据开始时间和结束时间返回时间段内的时间集合
     *
     * @param beginDate
     * @param endDate
     * @return List
     */
    public static List<String> getDates(Date beginDate, Date endDate) {
        List<String> lDate = new ArrayList<String>();
        lDate.add(String.valueOf(beginDate.getDate()));// 把开始时间加入集合
        Calendar cal = Calendar.getInstance();
        // 使用给定的 Date 设置此 Calendar 的时间
        cal.setTime(beginDate);
        boolean bContinue = true;
        while (bContinue) {
            // 根据日历的规则，为给定的日历字段添加或减去指定的时间量
            cal.add(Calendar.DAY_OF_MONTH, 1);
            // 测试此日期是否在指定日期之后
            if (endDate.after(cal.getTime())) {
                lDate.add(String.valueOf(cal.getTime().getDate()));
            } else {
                break;
            }
        }
        lDate.add(String.valueOf(endDate.getDate()));// 把结束时间加入集合
        return lDate;
    }
}
